# encoding=utf-8
import zipfile
from io import BytesIO

from flask import Flask, render_template, request, redirect, url_for, send_from_directory, send_file
import os
import dataAnalyse
import getData
from docx import Document

UPLOAD_FOLDER = os.path.curdir + os.path.sep + 'uploads' + os.path.sep
ALLOWED_EXTENSIONS = {'txt', 'docx'}
app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER


@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'GET':
        text = '请输入内容'
        if len(os.listdir(UPLOAD_FOLDER)) != 0:
            filename = os.listdir(UPLOAD_FOLDER)[0]
            filePath = 'uploads/' + filename
            if filename.split('.')[-1] == 'docx':
                document = Document(filePath)  # 打开文件
                text = ''
                for paragraph in document.paragraphs:
                    text = text + paragraph.text
            elif filename.split('.')[-1] == 'txt':
                file = open(filePath)
                text = file.read()
                print(text)
                file.close()
            os.remove(UPLOAD_FOLDER + filename)
        text = text.replace("\u00A0", "")
        text = text.replace("\u0020", "")
        text = text.replace("\u3000", "")
        spiderNum = len(os.listdir('cases'))
        print(spiderNum)
        return render_template('index.html', content=text,spiderNum=spiderNum)
    if request.method == 'POST':
        data = request.form.get('inputArea')
        save('saveTXT/文书.txt', data)
        DA = dataAnalyse.DataAnalyse()
        Boxes = DA.analyseText(data)
        people = request.form.get('people')
        birthplace = request.form.get('destinations')
        crimes = request.form.get('crimes')
        courts = request.form.get('courts')
        results = request.form.get('results')
        states = request.form.get('states')
        peoplechecked = request.form.get('peopleboxes1')
        print(peoplechecked)
        Nouns = DA.getNoun(data, DA.wordAndNature)
        Adjs = DA.getAdj(data, DA.wordAndNature)
        Verbs = DA.getVerb(data, DA.wordAndNature)

        pushBoxes = Boxes
        pushstates = pushBoxes.get("Character")
        pushresults = pushBoxes.get("Results")
        pushcourts = pushBoxes.get("Courts")
        pushcrimes = pushBoxes.get("Crimes")
        pushbirthplace = pushBoxes.get("Birthplace")
        pushraces = pushBoxes.get("Ethnicity")
        pushpeople = pushBoxes.get("Criminals")

        if len(people) != 0:
            Boxes['Criminals'] = people[:-1].split(";")
        races = request.form.get('races')
        if len(races) != 0:
            Boxes['Ethnicity'] = races[:-1].split(";")
        if len(birthplace) != 0:
            Boxes['Birthplace'] = birthplace[:-1].split(";")
        if len(courts) != 0:
            Boxes['Courts'] = courts[:-1].split(";")
        if len(crimes) != 0:
            Boxes['Crimes'] = crimes[:-1].split(";")
        if len(results) != 0:
            Boxes['Results'] = results[:-1].split(";")
        if len(states) != 0:
            Boxes['Character'] = states[:-1].split(";")
        DA.saveFile(Boxes, "文书")
        spiderNum = len(os.listdir('cases'))
        print(spiderNum)
        return render_template('index.html', content=data, content2=Boxes, Nouns=Nouns, Adjs=Adjs,
                               Verbs=Verbs, pushpeople=pushpeople, pushraces=pushraces, pushbirthplace=pushbirthplace,
                               pushcourts=pushcourts, pushcrimes=pushcrimes, pushresults=pushresults,
                               pushstates=pushstates,spiderNum=spiderNum)


def save(filename, contents):
    fh = open(filename, 'w', encoding='utf-8')
    fh.write(contents)
    fh.close()


def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'GET':
        return render_template('upload.html')
    if request.method == 'POST':
        file = request.files.get('uploadfiles')
        if file and allowed_file(file.filename):
            filename = file.filename
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect('/')


@app.route('/download/JSON', methods=['GET', 'POST'])
def download_json_file():
    if request.method == "GET":
        if os.path.isfile('saveJSON/文书_标注.json'):
            return send_from_directory('saveJSON/', "文书_标注.json", as_attachment=True)


@app.route('/download/TXT', methods=['GET', 'POST'])
def download_txt_file():
    if request.method == "GET":
        if os.path.isfile('saveTXT/文书.txt'):
            return send_from_directory('saveTXT/', "文书.txt", as_attachment=True)


@app.route('/spider', methods=['GET', 'POST'])
def spider_file():
    if request.method == 'GET':
        root_path = os.path.curdir + os.path.sep + 'cases' + os.path.sep
        for root, dirs, files in os.walk(root_path):
            for file in files:
                os.remove(root + file)
        return render_template('spider.html')
    if request.method == 'POST':
        num = request.form.get('num')
        demo = getData.wenshu()
        demo.saveAnlis(num)
        return redirect('/')


@app.route('/download/spiderCases', methods=['GET', 'POST'])
def download_spiderCases_file():
    zipf = zipfile.ZipFile('zip/spiderCases.zip', 'w', zipfile.ZIP_DEFLATED)
    root_path = os.path.curdir + os.path.sep + 'cases' + os.path.sep
    for root, dirs, files in os.walk(root_path):
        for file in files:
            zipf.write(root + file, file)
    zipf.close()
    return send_from_directory('zip/', "spiderCases.zip", as_attachment=True)


if __name__ == '__main__':
    app.run()
